var express = require('express');
var router = express.Router();

const MyQuery = require('../utils/db')

/* GET home page. */
router.get('/', function (req, res, next) {
  //res.render('index', { title: 'Express' });
  res.send('my is index page')
});


router.get('/login', function (req, res, next) {
  res.render('login');

});

router.get('/register', function (req, res, next) {
  res.render('register');

});

router.post('/register', async function (req, res, next) {
  //解构的默认值写法
  let {username='',pass1='',pass2=''} = req.body
  // req.body.username

  //做一些必要的判断 用户名和密码不能为空
  if( username == '' || pass1 == '' || !pass2 ){
    res.send('用户名和密码不能为空')
    return
  }
  if( pass1 != pass2 ){
    res.send('两次密码不一致')
    return
  }

  //在插入之前判断用户名是否存在
  let sql1 = `SELECT * FROM users WHERE username='${username}'`
  let { result: result1 } = await MyQuery(sql1) //
  if (result1.length > 0) {
    res.send('用户名太香了~')
    return //return终止代码向下运行
  }


  //res.send(req.body)
  let sql2 = `INSERT INTO users (username,password) values ('${username}','${pass2}')`
  let { result: result2 } = await MyQuery(sql2) //{ err:123,result:123 }

  if (result2.affectedRows > 0) {
    res.send('注册成功')
  } else {
    res.send('注册失败')
  }


});

module.exports = router;



